package at.fhj.swd.pse.data;

import java.util.List;

import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import at.fhj.swd.pse.entities.User;

/**
 * @author Florian Maderbacher
 **/

@Named
public class UserDAOImpl implements UserDAO {
	@PersistenceContext
	private EntityManager m_em;
	
	public UserDAOImpl()
	{	
	}
	
	public UserDAOImpl(EntityManager em)
	{
		m_em = em;
	}

	@Override
	public User insert(final User entity) {
		if (entity != null) {			
			return m_em.merge(entity);
		} 
		else {
			throw new NullPointerException("User");
		}
	}

	@Override
	public User get(final int id) {		
		return m_em.find(User.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getAll() {
		final String hql = "SELECT u FROM User AS u";
		return m_em.createQuery(hql).getResultList();
	}

	@Override
	public void remove(final User entity) {
		throw new UnsupportedOperationException("UserDAO: Removal of users should not be possible");
	}

	@Override
	public User update(final User entity) {
		if (entity != null) {			
			return m_em.merge(entity);
		} 
		else {
			throw new NullPointerException("UserDAO: User is null");
		}
	}

	@Override
	public User getByLogin(final String username, final String password) {
		if ((username == null) || (username.length() == 0)) {
			throw new IllegalArgumentException("username");
		}
		if ((password == null) || (password.length() == 0)) {
			throw new IllegalArgumentException("password");
		}

		Query q = this.m_em.createQuery("select u from User u where u.username=:username and u.password=:password");
		q.setParameter("username", username);
		q.setParameter("password", password);

		return (User) q.getSingleResult();
	}

}
